<?php
namespace App\Admin\Actions\DdbUser;

use App\Actions\DdbUserAction;
use App\Imports\BaseInfoImport;
use App\Imports\DdbImport;
use App\Imports\FzdxImport;
use App\Imports\QcImport;
use App\Imports\QrImport;
use App\Models\AdminUser;
use App\Models\Config;
use App\Models\DdbFirst;
use App\Models\DdbUser;
use App\Policies\Admin\AdminPolicy;
use App\Policies\Admin\DdbPolicy;
use App\Policies\Admin\DdbUserPolicy;
use Dcat\Admin\Admin;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Contracts\LazyRenderable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class ImportForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public $cache_key = 'import_ddb_user';

    // 处理请求 
    public function handle(array $input)
    {
        $admin_user = AdminUser::find(Admin::user()->id);
        if (!$input['file']) {
            return $this->response()->error('请上传文件');
        }

        if (!file_exists(file_local_path($input['file']))) {
            return $this->response()->error('文件不存在');
        }

        if (!$input['zp'] || !file_exists(file_local_path($input['zp']))) {
            return $this->response()->error('请上传照片');
        }

        if (!DdbUserPolicy::make(null, $admin_user)->can_import()) {
            return $this->response()->error('无法上传');
        }
        try {
            DdbUserAction::make($admin_user)->import($input);
            return $this->response()->success('上传成功')->refresh();
        } catch (\Throwable $th) {
            Log::info("导入初选人员信息登记：" . $th->getMessage());
            return $this->response()->error($th->getMessage());
        }
    }

    public function form()
    {
        $tpl_file = "<a href='".admin_route('download.tpl', ['table' => (new DdbUser())->getTable()])."' class='download' target='_blank'>[下载模板]</a>";
        $this->file('file', '文件')->required()->url(admin_route('files.upload', ['dir' => 'ddb_users/words', 'unique_name' => true]))->autoUpload()->autoSave(false)
        ->accept('docx')->maxSize(150*1024)
        ->mimeTypes('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
        ->help('只允许上传office word docx格式的文件，文件大小不超过50M。内容请按照给出的模板进行填写。' . $tpl_file);
        $this->image('zp', '照片')->required()->url(admin_route('files.upload', ['dir' => 'ddb_users/avatars', 'unique_name' => true]))->autoUpload()->autoSave(false)->accept('jpg,jpeg,png')->maxSize(50*1024)
        ->help('只允许上传jpg,jpeg,png格式的图片。近期彩色免冠正面照片，照片底色一般为白色，宽高比为4:5。');
        $this->disableResetButton();
    }
}